package com.tal.bcc.pad.cloud.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;


/**
 * 字符串处理类
 * Created by Administrator on 2017/3/10.
 * modify by shixiaoqiang
 */

public class XesStringUtils {

    private static final String maskString = "****";
    private static final String mBlankString = "  ";
    private static final char maskChar = '*';
    private static final int ACCOUNT_DISPLAY_LENGTH = 20;

    static final byte[] HEX_CHAR_TABLE = {(byte) '0', (byte) '1', (byte) '2',
            (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7',
            (byte) '8', (byte) '9', (byte) 'a', (byte) 'b', (byte) 'c',
            (byte) 'd', (byte) 'e', (byte) 'f'};

    public static String getHexString(byte[] raw) {
        byte[] hex = new byte[2 * raw.length];
        int index = 0;

        for (byte b : raw) {
            int v = b & 0xFF;
            hex[index++] = HEX_CHAR_TABLE[v >>> 4];
            hex[index++] = HEX_CHAR_TABLE[v & 0xF];
        }

        String result = "";
        try {
            result = new String(hex, "ASCII");
        } catch (UnsupportedEncodingException e) {
            // e.printStackTrace();
        } catch (Exception e) {
            // e.printStackTrace();
        }
        return result;
    }

    /**
     * @param input
     * @return
     */
    static public String trim(String input) {
        if (input != null && input.length() > 0) {
            String empty = String.valueOf("　");
            String cr = String.valueOf("\r");
            String ln = String.valueOf("\n");
            input = input.trim();
            while (input.startsWith(empty) || input.startsWith(cr)
                    || input.startsWith(ln)) {
                input = input.substring(1, input.length()).trim();
            }
            while (input.endsWith(empty) || input.endsWith(cr)
                    || input.endsWith(ln)) {
                input = input.substring(0, input.length() - 1).trim();
            }
        }

        return input;
    }

    /**
     * 获取手机号
     *
     * @param number
     * @return
     * @author shixiaoqiang
     */
    public static String getMobile(String number) {
        if (TextUtils.isEmpty(number)) {
            return null;
        }

        // 去掉非数字
        number = number.replaceAll("\\D+", "").trim();
        int length = number.length();
        if (length < 11) {
            return null;
        }

        return number.substring(length - 11, length);
    }

    /**
     * 获取电话的格式化字符串 ， 如：135 6666 8888
     *
     * @param mobile
     * @return
     */
    public static String getPhoneFormat(String mobile) {
        if (XesCheckUtils.isMobile(mobile)) {
            StringBuffer buffer = new StringBuffer(mobile);
            buffer.insert(3, ' ');
            buffer.insert(8, ' ');
            return buffer.toString();
        }
        return mobile;
    }

    /**
     * 去掉字符串间所有的字符
     *
     * @param value 原字符串
     * @param str   要去掉的字符
     * @return
     * @author shixiaoqiang
     */
    public static String replaceAllStr(String value, String str) {
        return value.replaceAll(str, "").trim();
    }

    /**
     * 隐藏手机号码中间四位
     *
     * @param phone
     * @return
     */
    public static String maskPhone(String phone) {
        if (XesCheckUtils.isMobile(phone)) {
            StringBuilder buffer = new StringBuilder();
            buffer.append(phone.substring(0, 3));
            buffer.append(maskString);
            buffer.append(phone.substring(7, 11));
            return buffer.toString();
        }
        return phone;
    }

    /**
     * 获取隐藏后的邮箱
     */
    public static String maskEmail(String email) {

        if (TextUtils.isEmpty(email) || email.length() <= 3) {
            return email;
        }

        StringBuilder sb = new StringBuilder(email);
        sb.delete(0, 3);
        sb.insert(0, maskChar);
        sb.insert(0, maskChar);
        sb.insert(0, maskChar);
        return sb.toString();
    }

    /**
     * 获取隐藏后的账号名
     *
     * @param account
     * @return
     */
    public static String maskAccount(String account) {
        if (XesCheckUtils.isMobile(account)) {
            return maskPhone(account);
        }
        if (XesCheckUtils.isEmail(account)) {
            return maskEmail(account);
        }
        return account;
    }

    /**
     * 获取隐藏后的账号名
     *
     * @return
     */
    public static String maskRealname(String realname) {

        if (TextUtils.isEmpty(realname)) {
            return "";
        }

        return new StringBuilder(realname).deleteCharAt(0).insert(0, "*")
                .toString();
    }

    /**
     * 获取隐藏后的账号名
     *
     * @return
     */
    public static String maskIDCard(String idCard) {
        // 新的掩码规则，下一个版本上
        // if (TextUtils.isEmpty(idCard)) {
        // return "";
        // } else if (idCard.length() < 10 ) { // 证件号码小于10位，用12***9表示
        // return new StringBuilder(idCard).replace(2, idCard.length() - 1,
        // "***").toString();
        // } else { // 证件号码大于等于10位，用123******9表示
        // return new StringBuilder(idCard).replace(3, idCard.length() - 1,
        // "******").toString();
        //
        // }
        if (TextUtils.isEmpty(idCard)) {
            return "";
        }
        return new StringBuilder(idCard).replace(3, idCard.length() - 1,
                "******").toString();
    }

    /**
     * 隐藏银行卡号
     *
     * @param bankCard
     * @return
     */
    public static String getMaskbankCard(String bankCard) {

        if (!XesCheckUtils.isBankCard(bankCard)) {
            return bankCard;
        }

        int index = 0;
        int length = bankCard.length();
        int duan = (length - 4) / 4;
        int yu = (length - 4) % 4;

        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < duan; i++) {
            buffer.append(maskString);
            buffer.append(mBlankString);
            index += 4;
        }

        for (int i = 0; i < yu; i++) {
            buffer.append(maskChar);
            index++;
        }

        buffer.append(bankCard, index, index + (4 - yu));
        index += 4 - yu;

        buffer.append(mBlankString);
        buffer.append(bankCard, index, length);

        return buffer.toString();
    }

    /**
     * 格式化卡号 如1234 5678 1234 5678
     *
     * @return
     */
    public static String formatCardNum(String cardNum) {
        if (!XesCheckUtils.isBankCard(cardNum)) {
            return cardNum;
        }
        StringBuilder formated = new StringBuilder();

        int length = cardNum.length();
        for (int i = 0; i < length; i++) {
            char c = cardNum.charAt(i);
            formated.append(c);
            if ((i + 1) % 4 == 0) {
                formated.append(" ");
            }
        }

        return formated.toString().trim();
    }

    /**
     * 获取银行卡号后四位
     *
     * @param bankCard
     * @return
     */
    public static String getBankCardTail4(String bankCard) {
        if (bankCard != null && bankCard.length() > 4) {
            return bankCard.substring(bankCard.length() - 4, bankCard.length());
        }
        return bankCard;
    }

    /**
     * 获取截断的账户名
     *
     * @param account
     * @return
     */
    public static String getCutAccount(String account) {
        if (!TextUtils.isEmpty(account)
                && account.length() > ACCOUNT_DISPLAY_LENGTH) {
            StringBuilder buffer = new StringBuilder();
            buffer.append(account.substring(0, ACCOUNT_DISPLAY_LENGTH - 1));
            buffer.append("...");
            return buffer.toString();
        }
        return account;
    }

    /**
     * 获取短信验证码
     *
     * @return
     * @author wyqiuchunlong
     */
    public static String getCheckCode(String checkCode) {
        Pattern p = Pattern.compile("(?<!\\d)(\\d{6})(?!\\d)");
        Matcher m = p.matcher(checkCode);
        if (m.find()) {
            return m.group(1);
        }
        return "";
    }

    /**
     * 截取精确到时分秒的data字符串前X位
     */
    public static String getFirstSubStrings(String origin, int firstNums) {
        if (origin == null) {
            return "";
        }
        if (origin.length() < firstNums) {
            firstNums = origin.length();
        }

        return origin.substring(0, firstNums);
    }

    /**
     * 将手机号中的区号+86去掉
     *
     * @param mobile
     * @return
     */
    public static String removeAreaCodeFromPhone(String mobile) {
        if (TextUtils.isEmpty(mobile)) {
            return mobile;
        }
        return mobile.replace("+86", "");
    }

    /**
     * 删除手机号中的区号，删除后如果手机号位数应该11位
     *
     * @param mobile
     * @return null表示手机号不合法，有string返回表示删除了区号的合法手机号
     */
    public static String convertToValidPhoneNumber(String mobile) {
        String phoneNumber = removeAreaCodeFromPhone(mobile);
        if (phoneNumber != null && phoneNumber.length() == 11) {
            return phoneNumber;
        }
        return null;
    }

    /**
     * 去掉错有非数
     *
     * @param charSequence
     * @return
     */
    public static String replaceNonNumber(String charSequence) {
        if (TextUtils.isEmpty(charSequence)) {
            return charSequence;
        }
        Pattern p = Pattern.compile("[^0-9]");
        Matcher m = p.matcher(charSequence);
        charSequence = m.replaceAll("");
        return charSequence;
    }

    /**
     * 判断两个string是否相同，包括判空
     *
     * @param str1
     * @param str2
     * @return
     */
    public static boolean compareString(String str1, String str2) {
        if (TextUtils.isEmpty(str1) && !TextUtils.isEmpty(str2)) {
            return false;
        } else if (!TextUtils.isEmpty(str1) && TextUtils.isEmpty(str2)) {
            return false;
        } else if (!TextUtils.isEmpty(str1) && !TextUtils.isEmpty(str2)
                && !str1.equals(str2)) {
            return false;
        }
        return true;
    }

    /**
     * 判断字符串是否为null或长度为0
     *
     * @param s 待校验字符串
     * @return {@code true}: 空<br> {@code false}: 不为空
     */
    public static boolean isEmpty(CharSequence s) {
        return s == null || s.length() == 0;
    }

    /**
     * 判断字符串是否为null或全为空格
     *
     * @param s 待校验字符串
     * @return {@code true}: null或全空格<br> {@code false}: 不为null且不全空格
     */
    public static boolean isSpace(String s) {
        return (s == null || s.trim().length() == 0);
    }


    /**
     * 返回字符串长度
     *
     * @param s 字符串
     * @return null返回0，其他返回自身长度
     */
    public static int length(CharSequence s) {
        return s == null ? 0 : s.length();
    }


    /**
     * 转化为半角字符
     *
     * @param s 待转字符串
     * @return 半角字符串
     */
    public static String toDBC(String s) {
        if (isEmpty(s)) return s;
        char[] chars = s.toCharArray();
        for (int i = 0, len = chars.length; i < len; i++) {
            if (chars[i] == 12288) {
                chars[i] = ' ';
            } else if (65281 <= chars[i] && chars[i] <= 65374) {
                chars[i] = (char) (chars[i] - 65248);
            } else {
                chars[i] = chars[i];
            }
        }
        return new String(chars);
    }

    /**
     * 转化为全角字符
     *
     * @param s 待转字符串
     * @return 全角字符串
     */
    public static String toSBC(String s) {
        if (isEmpty(s)) return s;
        char[] chars = s.toCharArray();
        for (int i = 0, len = chars.length; i < len; i++) {
            if (chars[i] == ' ') {
                chars[i] = (char) 12288;
            } else if (33 <= chars[i] && chars[i] <= 126) {
                chars[i] = (char) (chars[i] + 65248);
            } else {
                chars[i] = chars[i];
            }
        }
        return new String(chars);
    }

//    /**
//     * Description:文本复制到剪切板
//     *
//     * @param context
//     * @author strCopyText
//     */
//    public static boolean copyText(Context context, String strCopyText) {
//        try {
//            ClipboardManager cmb = (ClipboardManager) context
//                    .getSystemService(Context.CLIPBOARD_SERVICE);
//            cmb.setText(strCopyText);
//            return true;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return false;
//    }

    /**
     * 如果URL不是以HTTP开头加上HTTP
     *
     * @param strSource
     * @return
     */
    public static String getHttpWebURL(String strSource) {
        if (!TextUtils.isEmpty(strSource)) {
            String lowerCase = strSource.toLowerCase();
            if (!lowerCase.startsWith("http")) {
                return "http://" + lowerCase;
            }
        }
        return strSource;
    }


    /**
     * 电话号码中间显示*
     *
     * @param pNumber
     * @return
     */
    public static String getPhoneText(String pNumber) {
        StringBuilder sb = new StringBuilder();
        if (!TextUtils.isEmpty(pNumber) && pNumber.length() > 6) {
            for (int i = 0; i < pNumber.length(); i++) {
                char c = pNumber.charAt(i);
                if (i >= 3 && i <= 6) {
                    sb.append('*');
                } else {
                    sb.append(c);
                }
            }
            return sb.toString();
        }
        return pNumber;
    }

    public static String uncompressGzip(String input) {
        ByteArrayOutputStream out = null;
        ByteArrayInputStream bis = null;
        GZIPInputStream zip = null;

        String result = null;

        try {
            byte[] bytes = input.getBytes();
            bis = new ByteArrayInputStream(bytes);
            zip = new GZIPInputStream(bis);
            out = new ByteArrayOutputStream();

            byte[] buffer = new byte[20 * 1024];
            int readlen = 0;

            while ((readlen = zip.read(buffer)) > 0) {
                out.write(buffer, 0, readlen);
            }

            out.flush();

            result = out.toString();
        } catch (Exception e) {
            result = null;
        }

//        XesFileUtils.closeIO(zip, out, bis);

        return result;
    }

    /**
     * 裁剪字符串，数字和字母长度算1，汉子算2
     *
     * @param str
     * @param maxLength 字母或者英文的最大长度；汉子长度*2，偶数
     */
    public static String ellipsizeText(String str, int maxLength, String suffix, boolean needSuffix) {
        if (str == null || maxLength < 1) {
            return null;
        }
        String realSuffix = "…";
        if (needSuffix) {
            realSuffix += suffix;
        }
        int realSuffixLength = realSuffix.length() * 2;
        int suffixLength = suffix != null && needSuffix ? suffix.length() : 0;

        int totalLength = 0;
        String temp = null;
        int currentLength = 0;
        int strLength = str.length();
        for (int i = 0; i < strLength; i++) {
            temp = str.substring(i, i + 1);
            currentLength = charLength(temp);
            totalLength += currentLength;
            if ((totalLength + suffixLength) > maxLength) {
                while (totalLength + realSuffixLength > maxLength) {
                    totalLength -= currentLength;
                    i--;
                    if (i < 0) {
                        break;
                    }
                    temp = str.substring(i, i + 1);
                    currentLength = charLength(temp);
                }

                if (i + 2 < realSuffix.length()) {
                    return realSuffix;
                }
                return str.substring(0, i + 1) + realSuffix;

            }

        }
        return str + (needSuffix ? suffix : "");
    }

    private static String getStringByIndex(String str, int index) {
        return str.substring(index, index + 1);
    }


    private static final String CHINESE_REG = "[\u4e00-\u9fa5]";

    private static int charLength(String ch) {
        if (ch == null) {
            return 0;
        } else if (ch.matches(CHINESE_REG)) {
            return 2;
        } else {
            return 1;
        }
    }

    /**
     * 去掉脱敏的手机号之前的区号
     *
     * @param strPhone
     * @return
     */
    public static String removePhoneCode(String strPhone) {
        if (!TextUtils.isEmpty(strPhone)) {
            int indexOf = strPhone.indexOf(")");
            if (indexOf > 0) {
                return strPhone.substring(indexOf + 1);
            }
        }
        return "";
    }

    public static String getHeadName(String nikeName) {
        if (TextUtils.isEmpty(nikeName) || TextUtils.isEmpty(nikeName.trim())) {
            return "";
        }
        String headerName = nikeName.trim();
        if (headerName.length() > 2) {
            return nikeName.substring(headerName.length() - 2);
        } else {
            return headerName;
        }

    }

    public static String getWxTimeString(boolean showSuffix, long timestamp) {
        String result = "";
        String[] weekNames = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        String yearTimeSingleFormat = "yyyy-MM-dd";
        try {
            Calendar todayCalendar = Calendar.getInstance();
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(timestamp);
            if (todayCalendar.get(Calendar.YEAR) == calendar.get(Calendar.YEAR)) {
                if (todayCalendar.get(Calendar.DAY_OF_YEAR) - calendar.get(Calendar.DAY_OF_YEAR) < 7) {
                    int temp = todayCalendar.get(Calendar.DAY_OF_YEAR) - calendar.get(Calendar.DAY_OF_YEAR);
                    switch (temp) {
                        case 0://今天
                            result = getHourTime(timestamp);
                            break;
                        case 1://昨天
                            result = "昨天" + (showSuffix ? " " + getHourTime(timestamp) : "");
                            break;
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
                            result = weekNames[dayOfWeek - 1] + " " + (showSuffix ? getHourTime(timestamp) : "");
                            break;
                        default:
                            result = showSuffix ? getTime(timestamp, yearTimeSingleFormat) + " " + getHourTime(timestamp) : getTime(timestamp, yearTimeSingleFormat);
                            break;
                    }

                } else {
                    result = showSuffix ? getTime(timestamp, yearTimeSingleFormat) + " " + getHourTime(timestamp) : getTime(timestamp, yearTimeSingleFormat);

                }
            } else {
                result = showSuffix ? getTime(timestamp, yearTimeSingleFormat) + " " + getHourTime(timestamp) : getTime(timestamp, yearTimeSingleFormat);
            }

            return result;
        } catch (Exception e) {
            return "";
        }
    }

    private static String getHourTime(long timeStamp) {
        String hourTimeFormat = "HH:mm";
        String hourTime12Format = "hh:mm";
        //判断时间制
        if (is24Hour()) {
            //24小时制
            return getTime(timeStamp, hourTimeFormat);
        } else {
            //12小时制
            Calendar mCalendar = Calendar.getInstance();
            mCalendar.setTime(new Date(timeStamp));
            String pre = "";
            if (mCalendar.get(Calendar.AM_PM) == Calendar.AM) {
                pre = "上午";
            } else {
                pre = "下午";
            }
            String time = getTime(timeStamp, hourTime12Format);
            String[] hourMinute = time.split(":");
            if (hourMinute != null && hourMinute.length == 2) {
                int hour = Integer.parseInt(hourMinute[0]);
                time = hour + ":" + hourMinute[1];
            }
            return pre + time;
        }
    }


    public static boolean is24Hour() {
        return true;
//        return DateFormat.is24HourFormat(FrameUtilsContext.getContext());
    }

    public static String getTime(long time, String pattern) {
        Date date = new Date(time);
        return dateFormat(date, pattern);
    }

    private static String dateFormat(Date date, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }


    /**
     * 保留几位小数
     */
    public static String saveDecimals(int cnt, double value) {
        if (cnt == 2)
            return String.format("%.02f", value);
        else if (cnt == 1)
            return String.format("%.01f", value);
        else
            return String.format("%.0f", value);
    }

    /**
     * 获取英文字符个数.
     *
     * @param str
     * @return
     */
    public static long getTextCharCount(String str) {
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            count += str.charAt(i) < 128 ? 1 : 2;
        }
        return count;
    }

    @Deprecated
    public static String handleText(String str, int maxLen) {
        if (TextUtils.isEmpty(str)) {
            return str;
        }

        int count = 0;
        int endIndex = 0;
        for (int i = 0; i < str.length(); i++) {
            char item = str.charAt(i);
            if (item < 128) {
                count = count + 1;
            } else {
                count = count + 2;
            }
            if (maxLen == count || (item >= 128 && maxLen + 1 >= count)) {
                endIndex = i;
            }
        }
        if (count <= maxLen) {
            return str;
        } else {
            return str.substring(0, endIndex) + "...";
        }
    }

    /**
     * 截取文字，并补...
     * Offset 为从后面算起第几个字符替换.
     *
     * @param str
     * @param maxLen     保留长度
     * @param tailOffset default is 1
     * @return
     */
    public static String handleText(String str, int maxLen, int tailOffset) {
        if (TextUtils.isEmpty(str)) {
            return str;
        }
        if (getTextCharCount(str) <= maxLen) {
            return str;
        }
        int count = 0;
        int tempStep;
        int i = 0;
        for (; i < str.length(); i++) {
            tempStep = str.charAt(i) < 128 ? 1 : 2;
            count += tempStep;
            if (count == (maxLen - tailOffset)) {
                break;
            } else if (count > maxLen - tailOffset) {
                --i;
                break;
            }
        }

        return str.substring(0, i + 1) + "...";
    }

    /**
     * 截取字符串
     *
     * @param str
     * @param maxLen 中文为2个字符，英文为1个
     * @return
     */
    public static String subText(String str, int maxLen) {
        if (TextUtils.isEmpty(str)) {
            return str;
        }
        int count = 0;
        int tempStep;
        int i = 0;
        for (; i < str.length(); i++) {
            char item = str.charAt(i);
            tempStep = item < 128 ? 1 : 2;
            count += tempStep;
            if (maxLen == count) {
                break;
            } else if (item >= 128 && maxLen + 1 == count) {
                --i;
                break;
            }
        }
        if (count < maxLen) {
            return str;
        } else {
            return str.substring(0, i + 1);
        }
    }

//    public static void main(String[] args) {
//        String[] strArray = {"A", "ABCDEF", "ABCDEFGH", "ABCDEFGHIJ", "你ABC号码吗ABCDEFGHIJ", "你号码吗ABCDEFGHIJ", "你i号码ABCDEFGHIJ"};
//        for (int i = 0; i < strArray.length; i++) {
//            System.out.println(i + " subText   -->" + strArray[i] + "     " + subText(strArray[i], 8));
//            System.out.println(i + " handleText-->" + strArray[i] + "     " + handleText(strArray[i], 8));
//            System.out.println(i + " handleText-->" + strArray[i] + "     " + handleText(strArray[i], 8, 1));
//            System.out.println(i + " handleText-->" + strArray[i] + "     " + handleText(strArray[i], 8, 2));
//            System.out.println(i + " handleText-->" + strArray[i] + "     " + handleText(strArray[i], 8, 3));
//            System.out.println("------");
//        }
//    }


//    /***
//     * 读取assets
//     *
//     * @param fileName
//     * @return
//     */
//    public static String getStringFromAssets(Context context, String fileName) {
//        try (InputStreamReader inputReader = new InputStreamReader(context.getResources().getAssets().open(fileName));
//             BufferedReader bufReader = new BufferedReader(inputReader)) {
//            String line = "";
//            StringBuilder result = new StringBuilder();
//            while ((line = bufReader.readLine()) != null) {
//                result.append(line);
//            }
//            return result.toString();
//        } catch (Exception e) {
//            return null;
//        }
//    }

    /**
     * 利用正则表达式判断字符串是否是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 是否有中英文混排的情况.
     *
     * @param str
     * @return 全部中文字符为true，否则为false
     */
    public static boolean hasLangMixed(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) < 128) {
                return true;
            }
        }
        return false;
    }
}
